import {
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter, Input, OnDestroy,
  OnInit,
  Output,
  Renderer,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';


import {SharedService} from "@shared/service/shared/shared.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Subject} from "rxjs/Subject";
import {DictAreaTreeVerSionVO, DictTreeNodeVO} from "@interface/index";



export class PlaceParam {
  provinceId: number;
  cityId: number;
  districtId: number;
  provinceName: string;
  cityName: string;
  districtName: string;
}

@Component({
  selector: 'seed-regio-picker',
  templateUrl: './regio-picker.component.html',
  styleUrls: ['./regio-picker.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class RegioPickerComponent implements OnInit, OnDestroy {

  provinces: DictAreaTreeVerSionVO; // 全部省市
  citys: Array<any> = []; // 選中的城市
  districts: Array<any> = []; // 選中的城市下所有的區

  currentTab = 'province';
  municipality = '北京市,天津市,上海市,重庆市,香港特别行政区,澳门特别行政区,台湾省';

  public currentCity: PlaceParam = {
    provinceId: null,
    cityId: null,
    districtId: null,
    provinceName: '请选择',
    cityName: '',
    districtName: ''
  };
  @ViewChild('content') content: ElementRef;
  @ViewChild('header') header: ElementRef;
  @ViewChild('nav') nav: ElementRef;
  @Output() complete: EventEmitter<PlaceParam> = new EventEmitter<PlaceParam>();
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  @Input() tier: number;

  constructor(public router: Router,
              public route: ActivatedRoute,
              public sharedService: SharedService,
              public cdref: ChangeDetectorRef,
              public elementRef: ElementRef,
              public renderer: Renderer,
              public toolsService: ToolsService) {

    this.tier = 3;
  }

  /**
   * 获取省份信息
   */
  getProvinces() {
    this.toolsService.showLoading();
    this.sharedService.getProvinces().subscribe((res) => {
      this.toolsService.hideLoading();
      if (res.result === '0') {
        const provinces = res.data.dictTreeNodeVOList;
        this.provinces = provinces;
        this.cdref.detectChanges();
      } else {
        this.toolsService.showToast(res.msg);
      }
    });
  }

  /**
   * 选择省份
   * @param province 省对象
   * @modify ouxh862 2017-12-11
   */
  pickProvince(province: DictTreeNodeVO) {
    const currentCity = this.currentCity;
    currentCity.provinceName = province.title;
    // 如果是一层就直接返回
    if (this.tier === 1) {
      currentCity.provinceId = province.areaId;
      this.goBack();
      return;
    }

    // 非直辖市|非行政区|非全国
    if (this.municipality.indexOf(province.title) < 0 && province.areaId != null) {
      currentCity.cityName = '请选择';
      currentCity.districtName = '';
      currentCity.provinceId = province.areaId;

      this.citys = province.dictTreeNodeList;
      this.currentTab = 'city';

    } else {
      this.handleCity(province);
    }
    this.cdref.detectChanges();
  }

  /**
   * 处理城市
   * @param province 省对象
   * @param currentCity 当前所选择的城市信息
   */
  handleCity(province: DictTreeNodeVO) {
    // 直辖市|行政区|全国
    const currentCity = this.currentCity;
    currentCity.cityName = '';
    currentCity.districtName = '请选择';
    this.currentTab = 'district';

    const firstCity = province.dictTreeNodeList[0];
    // currentCity.cityName = firstCity.title;

    if (firstCity.dictTreeNodeList.length > 0) { // 直辖市
      currentCity.provinceId = province.areaId;
      currentCity.cityId = firstCity.areaId;

      this.districts = firstCity.dictTreeNodeList;
    } else { // 行政区
      currentCity.provinceId = province.areaId;
      currentCity.cityId = province.areaId;

      this.districts = province.dictTreeNodeList;
    }
    this.cdref.detectChanges();
  }

  /**
   * 选择城市
   * @param city 城市对象
   */
  pickCity(city) {
    const currentCity = this.currentCity;
    currentCity.cityName = city.title;
    currentCity.cityId = city.areaId;

    // 如果是二层就直接返回
    if (this.tier === 2) {
      this.goBack();
      return;
    }
    if (city.dictTreeNodeList.length > 0) { // 所选城市下有区县
      currentCity.districtName = '请选择';
      this.currentTab = 'district';
      this.districts = city.dictTreeNodeList;
    } else { // 所选城市下无区县
      currentCity.districtId = null;
      currentCity.districtName = '';
      this.goBack();
    }

  }

  /**
   * 选择区县
   * @param district 区县对象
   */
  pickDistrict(district) {
    this.currentCity.districtId = district.areaId;
    this.currentCity.districtName = district.title;
    // console.log(this.currentCity)
    this.goBack();
  }

  /**
   * 返回到上级筛选页面
   */
  goBack() {
    this.complete.emit(this.currentCity); // 向父组件抛出数据
  }

  /**
   * 设置内容高度
   */
  setContentHeight() {
    const documentHeight = document.documentElement.clientHeight,
      headerHeight = this.header.nativeElement.clientHeight,
      navHeight = this.nav.nativeElement.clientHeight,
      contentHeight = documentHeight - headerHeight - navHeight;
    this.renderer.setElementStyle(this.content.nativeElement, 'height', contentHeight + 'px');
  }

  ngOnInit() {
    this.getProvinces();
    this.setContentHeight();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

